package com.za.plugin.transfer.func;


import com.za.plugin.pojo.Content;
import com.za.plugin.util.StrUtil;

// 把 date_format 的 " 换为 '
public class DateFormatFunctionTransfer implements FunctionTransfer {
    @Override
    public boolean isSupport(String sql) {
        return clearSpace(sql).contains("date_format(");
    }
    private String clearSpace(String sql) {
        return sql.toLowerCase().replaceAll("date_format\\s*\\(", "date_format(");
    }

    @Override
    public String transfer(String sql) {
        sql = sql.replaceAll("date_format\\s*\\(", "date_format(");
        if (sql.contains("date_format(")) {
            int idx = sql.indexOf("date_format(");
            while (idx >= 0) {
                Content expectContent = StrUtil.getExpectContent(sql, idx + 11);
                assert expectContent != null;
                String expectStr = expectContent.getExpectStr();
                int end = sql.indexOf(")", idx);
                int left = expectStr.indexOf("\"");
                int right = expectStr.indexOf("\"", left + 1);
                if (left >= 0 && right >= 0) {
                    sql = sql.substring(0, idx) + " date_format(" + expectStr.substring(0, left)
                            + "\'" + expectStr.substring(left + 1, right) + "\'" + expectStr.substring(right + 1) + " " + sql.substring(end);
                }
                idx = sql.indexOf("date_format(", idx + "date_format(".length());
            }
        }
        return sql;
    }
}
